package cn.hznc.configuration;
import cn.hznc.domain.entity.MinioProp;
import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * minio 核心配置类
 */
@Configuration
@EnableConfigurationProperties(MinioProp.class)
public class MinioConfig {

    @Autowired
    private MinioProp minioProp;

    /**
     * 获取 MinioClient
     *
     * @return
     */
    @Bean
    public MinioClient minioClient() throws Exception{
        // 使用MinIO服务的URL，端口，Access key和Secret key创建一个MinioClient对象
        MinioClient minioClient = MinioClient.builder().endpoint(minioProp.getEndpoint()).credentials(minioProp.getAccessKey() , minioProp.getSecretKey()).build();
        // 检查存储桶是否已经存在
        BucketExistsArgs bucket = BucketExistsArgs.builder().bucket(minioProp.getBucketName()).build();
        boolean isExist = minioClient.bucketExists(bucket);
        if(!isExist) {
            minioClient.makeBucket(MakeBucketArgs.builder().bucket(minioProp.getBucketName()).build());
        }
        return minioClient;
    }
}
